<route lang="json">
{
    "name": "noticeManage",
    "meta": {
        "title": "控制台-通知管理",
        "requiresAuth": true
    }
}
</route>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { createNotice, deleteNotice, getNoticeList, updateNotice } from '~/api/notice'
import { getNoticeCategoryList } from '~/api/notice-category'
import { formatDate } from '~/utils/tools'

// 定义通知接口类型
interface Notice {
  _id: string
  noticeId: string
  title: string
  content: string
  categoryId: {
    _id: string
    categoryId: string
    name: string
    flag: boolean
    createTime: string
    updateTime: string
  }
  flag: boolean
  createTime?: string
  updateTime?: string
  [key: string]: any
}

// 定义通知分类接口类型
interface NoticeCategory {
  _id: string
  categoryId: string
  name: string
  flag: boolean
  createTime?: string
  updateTime?: string
  [key: string]: any
}

// 通知列表数据
const noticeList = ref<Notice[]>([])
const loading = ref(false)

// 通知分类列表
const categoryList = ref<NoticeCategory[]>([])

// 表格分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

// 搜索条件
const searchForm = reactive({
  title: '',
  categoryId: '',
  status: '',
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('添加通知')
const formLoading = ref(false)

// 表单数据
const formData = reactive({
  id: '',
  title: '',
  content: '',
  categoryId: '',
  status: 1,
})

// 表单规则
const rules = {
  title: [{ required: true, message: '请输入通知标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入通知内容', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择通知分类', trigger: 'change' }],
}

const formRef = ref()

// 获取通知列表
async function fetchNoticeList() {
  loading.value = true
  try {
    const res = await getNoticeList()
    if (res && Array.isArray(res.list)) {
      noticeList.value = res.list
      pagination.total = res.total || res.list.length
      pagination.pageSize = res.pageSize || 10
      pagination.currentPage = res.pageNum || 1
    }
    else if (res && Array.isArray(res)) {
      noticeList.value = res
      pagination.total = res.length
    }
    else if (res && typeof res === 'object' && Array.isArray(res.data)) {
      noticeList.value = res.data
      pagination.total = res.data.length
    }
    else {
      noticeList.value = []
      pagination.total = 0
    }
  }
  catch (error) {
    console.error('获取通知列表失败:', error)
    ElMessage.error('获取通知列表失败')
    noticeList.value = []
    pagination.total = 0
  }
  finally {
    loading.value = false
  }
}

// 获取通知分类列表
async function fetchCategoryList() {
  try {
    const res = await getNoticeCategoryList()
    if (res && Array.isArray(res.list)) {
      categoryList.value = res.list
    }
    else if (res && Array.isArray(res)) {
      categoryList.value = res
    }
    else if (res && typeof res === 'object' && Array.isArray(res.data)) {
      categoryList.value = res.data
    }
    else {
      categoryList.value = []
    }
  }
  catch (error) {
    console.error('获取通知分类列表失败:', error)
    ElMessage.error('获取通知分类列表失败')
    categoryList.value = []
  }
}

// 处理分页变化
function handleCurrentChange(val: number) {
  pagination.currentPage = val
}

function handleSizeChange(val: number) {
  pagination.pageSize = val
  pagination.currentPage = 1
}

// 搜索
function handleSearch() {
  pagination.currentPage = 1
}

// 重置搜索
function resetSearch() {
  Object.assign(searchForm, {
    title: '',
    categoryId: '',
    status: '',
  })
  pagination.currentPage = 1
}

// 过滤数据
const filteredData = computed(() => {
  let result = [...noticeList.value]

  // 按标题筛选
  if (searchForm.title) {
    result = result.filter(item => item.title.includes(searchForm.title))
  }

  // 按分类筛选
  if (searchForm.categoryId) {
    result = result.filter(item => item.categoryId._id === searchForm.categoryId)
  }

  // 按状态筛选
  if (searchForm.status !== '') {
    result = result.filter(item => item.flag === (Number(searchForm.status) === 1))
  }

  return result
})

// 计算当前页的数据
const currentPageData = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return filteredData.value.slice(start, end)
})

// 打开添加对话框
function openAddDialog() {
  dialogTitle.value = '添加通知'
  Object.assign(formData, {
    id: '',
    title: '',
    content: '',
    categoryId: '',
    status: 1,
  })
  dialogVisible.value = true
}

// 打开编辑对话框
function openEditDialog(row: Notice) {
  dialogTitle.value = '编辑通知'
  Object.assign(formData, {
    id: row._id,
    title: row.title,
    content: row.content,
    categoryId: row.categoryId._id,
    status: row.flag ? 1 : 0,
  })
  dialogVisible.value = true
}

// 提交表单
async function submitForm() {
  if (!formRef.value)
    return

  await formRef.value.validate(async (valid: boolean) => {
    if (!valid)
      return

    formLoading.value = true
    try {
      const noticeData = {
        title: formData.title,
        content: formData.content,
        categoryId: formData.categoryId,
        status: formData.status,
      }

      if (formData.id) {
        // 编辑
        await updateNotice(formData.id, noticeData)
        ElMessage.success('更新通知成功')
      }
      else {
        // 添加
        await createNotice(noticeData)
        ElMessage.success('添加通知成功')
      }
      dialogVisible.value = false
      fetchNoticeList()
    }
    catch (error) {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
    finally {
      formLoading.value = false
    }
  })
}

// 删除通知
function handleDelete(row: Notice) {
  ElMessageBox.confirm('确定要删除该通知吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await deleteNotice(row._id)
      ElMessage.success('删除成功')
      fetchNoticeList()
    }
    catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 获取分类名称
function getCategoryName(category: any) {
  return category && category.name ? category.name : '-'
}

// 页面加载时获取数据
onMounted(() => {
  fetchNoticeList()
  fetchCategoryList()
})
</script>

<template>
  <div class="notice-manage-container">
    <div class="notice-header">
      <h2 class="notice-title">
        通知管理
      </h2>
      <el-button type="primary" @click="openAddDialog">
        添加通知
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <el-card shadow="hover" class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="通知标题">
          <el-input v-model="searchForm.title" placeholder="请输入通知标题" clearable />
        </el-form-item>
        <el-form-item label="通知分类">
          <el-select v-model="searchForm.categoryId" placeholder="请选择通知分类" clearable style="width: 180px;">
            <el-option
              v-for="item in categoryList"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 180px;">
            <el-option label="已发布" value="1" />
            <el-option label="草稿" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item class="w-full">
          <el-button type="primary" class="ml-auto" @click="handleSearch">
            搜索
          </el-button>
          <el-button class="mr-[90px]" @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 通知列表 -->
    <el-card shadow="hover" class="notice-card">
      <el-table v-loading="loading" :data="currentPageData" stripe border style="width: 100%">
        <!-- 序号列 -->
        <el-table-column type="index" label="序号" width="60" />

        <!-- 标题列 -->
        <el-table-column prop="title" label="通知标题" min-width="180" show-overflow-tooltip />

        <!-- 分类列 -->
        <el-table-column prop="categoryId.name" label="通知分类" width="120">
          <template #default="scope">
            {{ getCategoryName(scope.row.categoryId) }}
          </template>
        </el-table-column>

        <!-- 内容列 -->
        <el-table-column prop="content" label="通知内容" min-width="250" show-overflow-tooltip />

        <!-- 状态列 -->
        <el-table-column prop="flag" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.flag ? 'success' : 'info'">
              {{ scope.row.flag ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 创建时间列 -->
        <el-table-column prop="createTime" label="创建时间" min-width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>

        <!-- 更新时间列 -->
        <el-table-column prop="updateTime" label="更新时间" min-width="180">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="openEditDialog(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="filteredData.length"
          @size-change="handleSizeChange" @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" destroy-on-close>
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="通知标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入通知标题" />
        </el-form-item>
        <el-form-item label="通知分类" prop="categoryId">
          <el-select v-model="formData.categoryId" placeholder="请选择通知分类" style="width: 100%">
            <el-option
              v-for="item in categoryList"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="通知内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="6"
            placeholder="请输入通知内容"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">
              发布
            </el-radio>
            <el-radio :label="0">
              草稿
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="formLoading" @click="submitForm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.notice-manage-container {
  padding: 20px;

  .notice-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .notice-title {
      font-size: 20px;
      font-weight: 600;
      margin: 0;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .notice-card {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
